package net.qqxh.shiro;

import net.qqxh.persistent.JfSysUserData;
import net.qqxh.persistent.JfUserSimple;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

public class JfRealmSimple extends AuthorizingRealm {



    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        JfUserSimple jfUserSimple = (JfUserSimple) principalCollection.getPrimaryPrincipal();
        Set<String> roles = JfSysUserData.getPermissionsByUserName(jfUserSimple.getUserid());
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        JfUserSimple jfUserSimple = JfSysUserData.getUserByUserId(token.getUsername());
        if(jfUserSimple==null){
            return null;
        }
        return new SimpleAuthenticationInfo(jfUserSimple,jfUserSimple.getPwd() , getName());
    }




}
